package xml;

import chess.Piece;

import java.util.Iterator;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.Reader;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.events.XMLEvent;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.XMLStreamException;

public class ChessReader {
	
	public static Piece[] read(String file) {
		Piece[] pieces = new Piece[32];
		
		try {
			Reader reader = new FileReader(file);
			XMLInputFactory factory = XMLInputFactory.newInstance();
			XMLEventReader xmlEventReader = factory.createXMLEventReader(reader);

			// stuff
			String current = "";
			int i = 0;
			int x = 0, y = 0;
			boolean white = true;
			String type = "";
			
			while (xmlEventReader.hasNext()) {
				XMLEvent event = xmlEventReader.nextEvent();
				
				// start element
				if (event.isStartElement()) {
					StartElement startelement = event.asStartElement();
					current = startelement.getName().getLocalPart();
					
					// process the good stuff
					if (current.equals("piece")) {
						// iterate attribs
						Iterator<Attribute> attributes = startelement.getAttributes();
						while (attributes.hasNext()) {
							Attribute attribute = attributes.next();
							
							// search required fields
							if (attribute.getName().toString().equals("x"))
								x = Integer.valueOf(attribute.getValue().toUpperCase().charAt(0) - 'A' + 1).intValue();
							else if (attribute.getName().toString().equals("y"))
								y = Integer.valueOf(attribute.getValue()).intValue();
							else if (attribute.getName().toString().equals("white"))
								white = Boolean.valueOf(attribute.getValue()).booleanValue();
							else if (attribute.getName().toString().equals("type"))
								type = attribute.getValue();
						
						}

						pieces[i] = new Piece(x, y, white, type);
						System.out.println(pieces[i].stringRepresentation());
					}
				}
			}
		}
		catch (FileNotFoundException | XMLStreamException e) {
			// nothingness
		}
		
		return pieces;
	}	
}
